package main

import (
	"fmt"
	"time"
)

func write(intChan chan int) {

	for i := 0; i < 20; i++ {
		intChan <- i
		time.Sleep(time.Millisecond * 300)
	}

	close(intChan)

}

func read(intChan chan int, exitChan chan bool) {

	for {
		v, ok := <-intChan
		time.Sleep(time.Millisecond * 500)
		if !ok {
			break
		}

		fmt.Printf("read %v \n", v)
	}

	// exitChan关闭后要避免被再次操作,否则 panic: close of closed channel
	exitChan <- true
	// 将ok置为false
	close(exitChan)
}

func main() {
	//  make(chan int, 10)
	intChan := make(chan int)
	exitChan := make(chan bool, 1)

	go write(intChan)
	// 如果只有写,没有读的话,如果超过容量写入会阻塞也就会deadLock.

	go read(intChan, exitChan)

	fmt.Println("等待中....")
	// 读操作会阻塞线程
	flag, _ := <-exitChan
	fmt.Printf("结束 %v", flag)

}
